package com.example.baselibrary.util;

import android.Manifest;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.lang.reflect.Method;

import static android.support.v4.app.ActivityCompat.requestPermissions;

/**
 * 权限处理
 * Created by nanPengFei on 2016/12/21 14:11.
 */
public class SKPermissionUtils {
    private static SKPermissionUtils mInstance;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private SKPermissionUtils() {
    }

    public static SKPermissionUtils getInstance() {
        if (null == mInstance) {
            synchronized (SKPermissionUtils.class) {
                if (null == mInstance) {
                    mInstance = new SKPermissionUtils();
                }
            }
        }
        return mInstance;
    }


    /**
     * 判断是否拥有某种权限,第一次没有则弹窗询问,用户拒绝后，
     * 请到对应的Activity中重写onRequestPermissionsResult进行判断requestCode值进行相应提示
     *
     * @param activity
     * @param permission
     * @param requestCode
     * @return
     */
    private boolean requestPermission(Activity activity, String[] permission, int requestCode) {
        //默认没有权限
        boolean isHasPermission = false;
        if (ContextCompat.checkSelfPermission(activity, permission[0]) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(activity, permission, requestCode);
        } else {
            isHasPermission = true;
        }
        return isHasPermission;
    }

    /**
     * 相机权限申请
     */
    public static final int REQUEST_PERMISSION_CAMERA = 501;
    /**
     * SD卡权限申请
     */
    public static final int REQUEST_PERMISSION_SD = 502;
    /**
     * 录音权限申请
     */
    public static final int REQUEST_PERMISSION_AUDIO = 503;
    /**
     * 定位权限申请
     */
    public static final int REQUEST_PERMISSION_LOCATION = 504;
    /**
     * 挂载SD卡权限申请
     */
    public static final int REQUEST_PERMISSION_FILESYSTEMS = 505;
    /**
     * 获取读取手机通讯录
     */
    public static final int REQUEST_PERMISSION_CONTACTS = 506;
    /**
     * 一次申请多个全校所用
     */
    public static final int EXTERNAL_STORAGE_REQ_CODE = 100;
    /**
     * 状态
     */
    public static final int REQUEST_PERMISSION_STATE = 507;
    /**
     * SD卡和
     */
    public static final int REQUEST_PERMISSION_CSD_STATE = 508;


    /**
     * 关于权限申请
     * 一次申请多个权限所用 ---视频所用
     */
    public static final int EXTERNAL_STORAGE_REQ_CODE_VIDEO = 101;


    /**
     * 相机权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestCamera(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.CAMERA
                }, REQUEST_PERMISSION_CAMERA);
    }

    /**
     * SD卡权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestSD(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                }, REQUEST_PERMISSION_SD);
    }

    /**
     * 录音权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestAudio(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.RECORD_AUDIO
                }, REQUEST_PERMISSION_AUDIO);
    }

    /**
     * 定位权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestLocation(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION
                }, REQUEST_PERMISSION_LOCATION);
    }

    /**
     * 联系人权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestContacts(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.READ_CONTACTS,
                        Manifest.permission.WRITE_CONTACTS
                }, REQUEST_PERMISSION_CONTACTS);
    }

    /**
     * 挂载SD卡权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestFilesystems(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
                }, REQUEST_PERMISSION_FILESYSTEMS);
    }

    /**
     * 挂载SD卡权限申请
     *
     * @param activity
     * @return
     */
    public boolean requestStatesystems(Activity activity) {
        return requestPermission(activity,
                new String[]{Manifest.permission.READ_PHONE_STATE
                }, REQUEST_PERMISSION_STATE);
    }

    /**
     * 申请提供的所有权限
     *
     * @param activity
     */
    public void requestAll(Activity activity) {
        requestCamera(activity);
        requestSD(activity);
        requestAudio(activity);
        requestLocation(activity);
        requestFilesystems(activity);
    }


    /**
     * 一次申请多个权限
     */
    public boolean requestMorePermission(Activity activity) {
        return requestPermission(activity, new String[]
                {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE_VIDEO);
    }

    /**
     * 一次申请拍照SD卡权限
     */
    public boolean requestCarmaSDPermission(Activity activity) {
        return requestPermission(activity, new String[]
                {Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSION_CSD_STATE);

    }


    /**
     * 检查是否获得悬浮窗权限
     *
     * @param context
     * @param op
     * @return
     */
    //OP_SYSTEM_ALERT_WINDOW=24   op = 24
    public boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class<?> spClazz = Class.forName(manager.getClass().getName());
                Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int property = (Integer) method.invoke(manager, op,
                        Binder.getCallingUid(), context.getPackageName());

                if (AppOpsManager.MODE_ALLOWED == property) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {

            }
        } else {

        }
        return true;
    }


    /**
     * 跳转到miui的权限管理页面
     *
     * @param activity
     * @param requestTag
     */
    public void gotoMiuiPermission(Activity activity, int requestTag) {
        Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
        ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        i.setComponent(componentName);
        i.putExtra("extra_pkgname", activity.getPackageName());
        try {
            activity.startActivityForResult(i, requestTag);
        } catch (Exception e) {
            e.printStackTrace();
            gotoMeizuPermission(activity, requestTag);
        }
    }


    /**
     * 跳转到魅族的权限管理系统
     *
     * @param activity
     * @param requestTag
     */
    public void gotoMeizuPermission(Activity activity, int requestTag) {
        Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra("packageName", activity.getPackageName());
        try {
            activity.startActivityForResult(intent, requestTag);
        } catch (Exception e) {
            e.printStackTrace();
            gotoHuaweiPermission(activity, requestTag);
        }
    }

    /**
     * 华为的权限管理页面
     *
     * @param activity
     * @param requestTag
     */
    public void gotoHuaweiPermission(Activity activity, int requestTag) {
        try {
            Intent intent = new Intent(activity.getPackageName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager",
                    "com.huawei.systemmanager.addviewmonitor.AddViewMonitorActivity");
            intent.setComponent(comp);
            activity.startActivityForResult(intent, requestTag);
        } catch (Exception e) {
            e.printStackTrace();
            activity.startActivityForResult(getAppDetailSettingIntent(activity), requestTag);
        }
    }

    /**
     * 获取应用详情页面intent
     *
     * @param activity
     * @return
     */
    public Intent getAppDetailSettingIntent(Activity activity) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        return localIntent;
    }

   public boolean setCallPhonePermission(Activity mActivity, Application application) {
        // 检查是否获得了权限（Android6.0运行时权限）
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.CALL_PHONE)) {
                // 返回值：
                //如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                //如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                //如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                // 弹窗需要解释为何需要该权限，再次请求授权
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", application.getPackageName(), null);
                intent.setData(uri);
                mActivity.startActivity(intent);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
            }

        } else {
            return true;
        }
        return false;
    }

}